package be.ac.ua.pats.thesisrobotica.robot.sensors;

//~--- non-JDK imports --------------------------------------------------------

import be.ac.ua.pats.thesisrobotica.robot.constants.RobotConstants;
import be.ac.ua.pats.thesisrobotica.robot.communication.Connection;


/**
 * Implementation of the touchsensor
 *
 * @author Jimmy
 */
public class TouchSensor extends Sensor implements Runnable {

    public lejos.nxt.TouchSensor sensor;

    public TouchSensor() {
        this(null);
    }

    /**
     * @param connection The connection over which notifications should be sent
     */
    public TouchSensor(Connection connection) {
        super(connection);

        sensor = new lejos.nxt.TouchSensor(RobotConstants.SensorPorts.TOUCHSENSOR);
        type = RobotConstants.Types.TOUCHSENSOR;
    }

    /**
     * @return The current sensor reading
     */
    public String getValue() {
        return String.valueOf(sensor.isPressed());
    }

    /**
     * Constantly checks wether the sensor value has changed, taking into account the threshold and time interval,
     * if this happens the method will send a notification over the connection containg the sensor-ID and the value.
     */
    public void run() {
        Boolean            previousPressed    = false;
        boolean            currentPressed     = false;
        SensorNotification sensorNotification = new SensorNotification(connection);

        if (interval == 0) {
            while (connection.isConnected()) {
                currentPressed = sensor.isPressed();

                if (currentPressed != previousPressed) {
                    sensorNotification.setAndSend(this.id, currentPressed);

                    previousPressed = currentPressed;
                }
            }
        } else if(interval != 0) {
            Thread interrupterThread = new Thread(new InterrupterThread(Thread.currentThread(),sensor));
            while(connection.isConnected()) {
                try {
                    sensorNotification.setAndSend(this.id, sensor.isPressed());
                    interrupterThread.start();
                    Thread.sleep(interval);
                    interrupterThread.interrupt();
                } catch (InterruptedException ex) {
                }
            }
        }
    }

    public void setValue(String s) {
        throw new UnsupportedOperationException();
    }
}
